<template>
  <cs-form
    ref="formRef"
    v-model="store.basicFormData"
    :items="items"
    component-full-width
  />
</template>

<script setup lang="ts">
  import { computed, h, inject, reactive, toRef } from 'vue'
  import config from '/@/../.csdev/config.json'


  import type { BasicFormData, Store } from '../types'

  const store = inject('CSDEV_CODE_VIEW_STORE', {} as Store)
  const formRef = toRef(store, 'basicFormRef')

  /** 接口文件选项 */
  const apiFileOptions = computed(() => {
    const options = []

    for (const apiPath in store.apis) {
      const apiFilePath = apiPath.replace(/\/$/, '.ts')
      options.push({
        name: store.apis[apiPath].name,
        label: apiFilePath,
        value: apiPath
      })
    }
    return options
  })

  const items: FormItemProps<BasicFormData>[] = reactive([
    {
      label: '模块目录',
      prop: 'modulePath',
      component: 'el-input',
      required: true,
      rules: {
        trigger: 'blur',
        validator: (rule, value: string, callback) => {
          if (value === '') {
            return callback(new Error('请输入模块目录'))
          }
          if (!/^(?:[a-z]+(?:-[a-z]+)*)+(?:\/[a-z]+(?:-[a-z]+)*)*$/.test(value)) {
            return callback(new Error('模块目录需满足kebab-case的命名法'))
          }
          callback()
        }
      },
      props: {
        class: 'basic-form__module-path-input'
      },
      slots: {
        prefix: () => h('div', config.code.moduleRootPath)
      }
    },
    {
      label: '接口文件',
      prop: 'apiFilePath',
      component: 'cs-select',
      required: true,
      props: {
        options: apiFileOptions,
        fitInputWidth: true,
        filterable: true
      }
    }
  ])
</script>

<style lang="scss">
  .basic-form__module-path-input {
    .el-input__prefix-inner > :last-child {
      margin-right: 0;
    }
  }
</style>
